<template>
    <div class="post-management-container">
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="帖子标题">
            <el-input v-model="queryParams.title" placeholder="请输入标题" clearable />
          </el-form-item>
          <el-form-item label="作者">
            <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="内容类型">
            <el-select v-model="queryParams.contenttype" placeholder="请选择内容类型" clearable>
              <el-option
                v-for="item in contentTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间">
            <el-date-picker
              v-model="queryParams.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 操作按钮区域 -->
      <div class="operation-container">
        <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
          批量删除
        </el-button>
        <el-button type="warning" :disabled="!selectedIds.length" @click="handleBatchAudit(5)">
          批量驳回
        </el-button>
        <el-button type="success" :disabled="!selectedIds.length" @click="handleBatchAudit(1)">
          批量通过
        </el-button>
        <el-button type="info" @click="handleExport">
          导出数据
        </el-button>
      </div>
  
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="postList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="35" align="center" />
          <el-table-column prop="id" label="ID" width="50" align="center" />
          <el-table-column label="封面" width="120" align="center">
            <template #default="{ row }">
              <el-image
                :src="row.image"
                fit="cover"
                :preview-src-list="[row.image]"
                style="width: 100px; height: 70px; border-radius: 4px;"
              />
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
          <el-table-column prop="description" label="内容" min-width="380" show-overflow-tooltip />
          <el-table-column label="作者" width="140" align="center">
            <template #default="{ row }">
              <div class="user-info-cell" @click.stop="handleShowUserInfo(row.userid)">
                <el-avatar :src="row.avatar" />
                <span class="username">{{ row.username }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="媒体类型" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="mediaTypeMap[row.mediatype].type">
                {{ mediaTypeMap[row.mediatype].label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="statusMap[row.status].type">
                {{ statusMap[row.status].label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="viewcount" label="浏览" width="90" align="center" sortable />
          <el-table-column prop="likes" label="点赞" width="90" align="center" sortable />
          <el-table-column prop="commentcount" label="评论" width="90" align="center" sortable />
          <el-table-column prop="collectioncount" label="收藏" width="90" align="center" sortable />
          <el-table-column prop="createtime" label="发布时间" width="180" align="center" sortable>
            <template #default="{ row }">
              {{ row.createtime}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click.stop="showNoteDetailDialog(row)">
                预览
              </el-button>
              <el-dropdown trigger="click" @command="handleCommand($event, row)">
                <el-button size="small">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                    <el-dropdown-item v-if="row.status === 3" command="auditPass">审核通过</el-dropdown-item>
                    <el-dropdown-item v-if="row.status === 3" command="auditReject">审核驳回</el-dropdown-item>
                    <el-dropdown-item command="recommend">推荐</el-dropdown-item>
                    <el-dropdown-item command="statistics">数据统计</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
  
      <!-- 帖子预览对话框 -->
      <el-dialog
        v-model="previewVisible"
        title="帖子预览"
        width="80%"
        top="5vh"
        destroy-on-close
      >
        <post-preview :post-id="currentPostId" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="previewVisible = false">关闭</el-button>
            <el-button type="primary" @click="handleEditPost(currentPostId)">
              编辑
            </el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 用户信息对话框 -->
      <el-dialog
        v-model="userInfoVisible"
        title="用户信息"
        width="50%"
        destroy-on-close
      >
        <user-info :user-id="currentUserId" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="userInfoVisible = false">关闭</el-button>
            <el-button type="primary" @click="handleSendMessage(currentUserId)">
              发送消息
            </el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 审核对话框 -->
      <el-dialog
        v-model="auditVisible"
        :title="`${auditAction === 1 ? '通过' : '驳回'}审核`"
        width="50%"
        destroy-on-close
      >
        <el-form :model="auditForm" label-width="80px">
          <el-form-item label="审核意见" prop="reason">
            <el-input
              v-model="auditForm.reason"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="auditVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmAudit">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>

       <!-- 帖子详情弹窗 -->
    <el-dialog
      v-model="showNoteDetail"
      :fullscreen="isMobile"
      :show-close="false"
      custom-class="note-detail-dialog"
      @close="closeDetail"
    >
      <div class="note-detail-container">
        <!-- 左侧图片区域 - 全屏无间距 -->
        <div class="detail-left">
          <div class="image-container">
            <img :src="currentNote.images[currentImageIndex]" alt="note image" />
            <div v-if="currentNote.images.length > 1" class="side-nav-arrows">
              <div class="nav-arrow left" @click.stop="prevImage">
                <el-icon><ArrowLeft /></el-icon>
              </div>
              <div class="nav-arrow right" @click.stop="nextImage">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            <div v-if="currentNote.images.length > 1" class="dot-indicators">
              <div
                v-for="(img, index) in currentNote.images"
                :key="index"
                class="dot"
                :class="{ active: currentImageIndex === index }"
                @click.stop="currentImageIndex = index"
              ></div>
            </div>
          </div>
        </div>

        <!-- 右侧内容区域 - 可滚动 -->
        <div class="detail-right">
          <div class="scroll-content">
            <!-- 用户信息区域 -->
            <div class="user-info">
              <el-avatar :size="50" :src="currentNote.avatar" />
              <div class="user-meta">
                <span class="username">{{ currentNote.name }}</span>
                <span class="follow-count">{{ currentNote.followers }} 粉丝</span>
              </div>
              <el-button
                v-if="!currentNote.isFollowing"
                type="danger"
                round
                class="follow-btn"
                
              >
                关注
              </el-button>
              <el-button
                v-else
                type="info"
                round
                class="follow-btn"
               
              >
                已关注
              </el-button>
            </div>

            <el-divider />

            <!-- 帖子内容 -->
            <div class="note-content">
              <h2>{{ currentNote.title }}</h2>
              <p>{{ currentNote.content }}</p>
            </div>

            <el-divider />

            <!-- 评论区 -->
            <div class="comments-section">
              <h3>评论 ({{ currentNote.comments.length }})</h3>
              <div class="comment-list">
                <!-- 遍历嵌套评论 -->
                <template v-for="comment in nestedComments" :key="comment.id"  >
                  <!-- 渲染当前评论 -->
                 <div class="comment-item-xian">
                  

                  <div
                    class="comment-item"
                    :style="{ 'margin-left': comment.depth * 20 + 'px' }"
                  >
                    <el-avatar :size="40" :src="comment.avatar" />
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author">{{ comment.username }}</span>
                        <span class="comment-time">{{ formatTime(comment.createtime) }}</span>
                      </div>
                      <p class="comment-text">{{ comment.content }}</p>
                      <div v-if="comment.images" class="comment-images">
                        <img
                          v-for="(img, idx) in comment.images"
                          :key="idx"
                          :src="img"
                          alt="comment image"
                          @click="showImagePreview(img)"
                        />
                      </div>
                      <div class="comment-actions">
                        <span @click="likeComment(comment)">
                          <el-icon :class="['icon', { 'dianzan': comment.isdianzan }]"><Star /></el-icon> {{ comment.likes }}
                        </span>
                        <!-- <span @click="replyToComment(comment)">回复</span> -->
                      </div>
                    </div>
                  </div>

                  <!-- 递归渲染子评论 -->
                  <template v-if="comment.replies && comment.replies.length">
                  <div
                    v-for="reply in comment.replies"
                    :key="reply.id"
                    class="comment-item"
                    :style="{ 'margin-left': reply.depth * 20 + 'px' }"
                  >
                    <el-avatar :size="30" :src="reply.avatar" />
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author">{{ reply.username }}</span>
                        <span class="comment-time">{{ formatTime(reply.createtime) }}</span>
                      </div>
                      <p class="comment-text">
                        <template v-if="reply.replyusername">
                          <span class="reply-mention">回复 @{{ reply.replyusername }} : </span>
                        </template>
                        {{ reply.content }}
                      </p>
                      <div v-if="reply.images" class="comment-images">
                        <img
                          v-for="(img, idx) in reply.images"
                          :key="idx"
                          :src="img"
                          alt="comment image"
                          @click="showImagePreview(img)"
                        />
                      </div>
                      <div class="comment-actions">
                        <span @click="likeComment(reply)">
                          <el-icon :class="['icon', { 'dianzan': reply.isdianzan }]"><Star /></el-icon> {{ reply.likes }}
                        </span>
                        <!-- <span @click="replyToComment(reply)">回复</span> -->
                        
                      </div>
                    </div>
                  </div>
                </template>
                </div>
                </template>
              </div>
            </div>
          </div>
          <!-- 固定评论框 -->
          <div class="fixed-comment-input">
            <!-- 回复用户信息显示（当有回复对象时显示） -->
            <div v-if="replyingTo" class="reply-info">
              <span>回复 @{{ replyingTo.username }}</span>
              <el-icon class="close-reply" @click="cancelReply"><Close /></el-icon>
            </div>

            <!-- 正常模式（未聚焦输入框时） -->
            <div v-if="!isInputFocused" class="comment-normal-mode">
              <!-- 左侧输入框 -->
              <!-- <el-input
                v-model="newComment"
                placeholder="写下你的评论..."
                class="comment-input"
                @focus="handleInputFocus"
              /> -->
              
              <!-- 右侧操作按钮 -->
              <div class="action-buttons">
                <div class="action-item" >
                  <el-icon :class="['icon', { 'liked': currentNote.isliked }]"><Star /></el-icon>
                  <span>{{ currentNote.likes }}</span>
                </div>
                
                <div class="action-item"  >
                  <el-icon :class="['icon', { 'favorited': currentNote.isFavorited }]"><Collection /></el-icon>
                  <span>{{ currentNote.collectioncount }}</span>
                </div>
                
                <div class="action-item" >
                  <el-icon class="icon"><ChatDotRound /></el-icon>
                  <span>{{ currentNote.comments.length }}</span>
                </div>
                
                <div class="action-item" @click="shareNote">
                  <el-icon class="icon"><Share /></el-icon>
                  <span>分享</span>
                </div>
              </div>
            </div>

            <!-- 编辑模式（聚焦输入框时） -->
            <div v-else class="comment-edit-mode">
              <!-- 文本输入区（可自动扩展高度） -->
              <el-input
                v-model="newComment"
                type="textarea"
                :rows="textAreaRows"
                placeholder="写下你的评论..."
                class="comment-textarea"
                @input="adjustTextareaHeight"
              />
              
              <!-- 底部操作栏 -->
              <div class="edit-actions">
                <!-- 左侧功能按钮 -->
                <div class="left-actions">
                  <el-icon class="action-icon" @click="insertMention"><User /></el-icon>
                  <!-- 表情包预留位置 -->
                  <el-icon class="action-icon" @click="showEmojiPicker"><HelpFilled /></el-icon>
                  <el-icon class="action-icon" @click="showFavoriteEmojis"><Star /></el-icon>
                  <el-icon class="action-icon" @click="uploadImage">
                    <input 
                      type="file" 
                      ref="imageInput" 
                      accept="image/*" 
                      style="display: none" 
                      @change="handleImageUpload"
                    />
                    <Picture />
                  </el-icon>
                </div>
                
                <!-- 右侧操作按钮 -->
                <div class="right-actions">
                  <el-button class="cancel-btn" @click="cancelComment">取消</el-button>
                  <el-button 
                    class="send-btn" 
                    type="danger" 
                    :disabled="!newComment.trim()"
                    @click="submitComment(currentNote)"
                  >
                    发送
                  </el-button>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </el-dialog>


    </div>
  </template>
  
  <script setup>
  //npm install -D sass-embedded
  //npm install pinia
  import { ref, reactive, onMounted,computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown } from '@element-plus/icons-vue'
  import request from '../utils/request';
  import { useUserStore } from '../utils/userStore'
  const userStore = useUserStore()
  // 2. 创建响应式 users
const users = ref([])

// 3. 定义获取用户数据的函数
const fetchUsers = () => {
  debugger;
  const user = userStore.getUser
  users.value = user
  console.log(users.value)
}
  
  // 状态映射
  const statusMap = {
    0: { label: '草稿', type: 'info' },
    1: { label: '已发布', type: 'success' },
    2: { label: '已删除', type: 'danger' },
    3: { label: '审核中', type: 'warning' },
    4: { label: '被举报', type: 'danger' },
    5: { label: '审核驳回', type: 'danger' },
    6: { label: '待修改', type: 'warning' }
  }
  
  // 媒体类型映射
  const mediaTypeMap = {
    1: { label: '纯图文', type: '' },
    2: { label: '图文+视频', type: 'success' },
    3: { label: '纯视频', type: 'warning' },
    4: { label: '多图+视频', type: 'success' },
    5: { label: '直播回放', type: 'danger' }
  }
  
  // 状态选项
  const statusOptions = [
    { value: 0, label: '草稿' },
    { value: 1, label: '已发布' },
    { value: 2, label: '已删除' },
    { value: 3, label: '审核中' },
    { value: 4, label: '被举报' },
    { value: 5, label: '审核驳回' },
    { value: 6, label: '待修改' }
  ]
  
  // 内容类型选项
  const contentTypeOptions = [
    { value: 1, label: '普通' },
    { value: 2, label: '教程' },
    { value: 3, label: '测评' },
    { value: 4, label: '清单' },
    { value: 5, label: '问答' }
  ]
  
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    title: '',
    username: '',
    status: undefined,
    contenttype: undefined,
    dateRange: []
  })
  
  // 表格数据
  const postList = ref([])
  const loading = ref(false)
  const total = ref(0)
  const selectedIds = ref([])
  
  // 对话框控制
  const previewVisible = ref(false)
  const userInfoVisible = ref(false)
  const auditVisible = ref(false)
  const currentPostId = ref(null)
  const currentUserId = ref(null)
  const auditAction = ref(1) // 1通过 5驳回
  const auditForm = reactive({
    reason: ''
  })

    //预览弹窗
  const showNoteDetail = ref(false)
  const isMobile = ref(false)
  const currentImageIndex = ref(0)
  const newComment = ref('')
 
  const currentNote = ref({
  id: null,
  images: [],
  title: '',
  content: '',
  tags: [],
  comments: []
})
  
  // 获取帖子列表
  const getList = async () => {
    try {
      loading.value = true
      const params = {
        ...queryParams,
        startTime: queryParams.dateRange?.[0],
        endTime: queryParams.dateRange?.[1]
      }
      delete params.dateRange
      
      const res = await  request.post('/xhs/main/getMainListEdit',params)  
      debugger
      //const res = ref()
      postList.value = res.data.records
      // 获取用户信息
      const userIds = [...new Set(res.data.records.map(item => item.userid))]
      //await fetchUserInfo(userIds)
      
      total.value = res.data.total
    } catch (error) {
      console.error('获取帖子列表失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  // 获取用户信息
  const fetchUserInfo = async (userIds) => {
    try {
      //const userPromises = userIds.map(id => getUserInfo(id))
      const userPromises = ref("");
      const users = await Promise.all(userPromises)
      
      const userMap = {}
      users.forEach(user => {
        if (user.data) {
          userMap[user.data.id] = user.data
        }
      })
      
      postList.value = postList.value.map(post => ({
        ...post,
        user: userMap[post.userid] || null
      }))
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
  
  // 搜索
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }
  
  // 重置搜索
  const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.title = ''
    queryParams.username = ''
    queryParams.status = undefined
    queryParams.contenttype = undefined
    queryParams.dateRange = []
    getList()
  }
  
  // 分页大小改变
  const handleSizeChange = (val) => {
    queryParams.pageSize = val
    getList()
  }
  
  // 当前页改变
  const handleCurrentChange = (val) => {
    queryParams.pageNum = val
    getList()
  }
  
  // 表格行选择
  const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id)
  }
  
//   // 表格行点击
//   const handleRowClick = (row) => {
//     currentPostId.value = row.id
//     previewVisible.value = true
//   }
  
  // 预览帖子
  const handlePreview = (row) => {
    debugger;
    currentPostId.value = row.id
    previewVisible.value = true
  }
  
  // 显示用户信息
  const handleShowUserInfo = (userId) => {
    currentUserId.value = userId
    userInfoVisible.value = true
  }
  
  // 发送消息
  const handleSendMessage = (userId) => {
    console.log('发送消息给用户:', userId)
    userInfoVisible.value = false
    ElMessage.success('消息功能待开发')
  }
  
  // 编辑帖子
  const handleEditPost = (postId) => {
    console.log('编辑帖子:', postId)
    previewVisible.value = false
    ElMessage.success('编辑功能待开发')
  }
  
  // 更多操作
  const handleCommand = (command, row) => {
    switch (command) {
      case 'edit':
        handleEditPost(row.id)
        break
      case 'delete':
        handleDelete(row)
        break
      case 'auditPass':
        handleAudit(row.id, 1)
        break
      case 'auditReject':
        handleAudit(row.id, 5)
        break
      case 'recommend':
        handleRecommend(row)
        break
      case 'statistics':
        handleStatistics(row)
        break
      default:
        break
    }
  }
  
  // 删除帖子
  const handleDelete = (row) => {
    debugger;
    ElMessageBox.confirm(`确认删除标题为"${row.title}"的帖子吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        debugger;
        // await deletePost(row.id)
        const res = await  request.post('/xhs/main/deleteMainById',{"id":row.id})  
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error('删除失败:', error)
      }
    }).catch(() => {
      debugger;
      ElMessage.info('已取消删除')
    })
  }
  
  // 批量删除
  const handleBatchDelete = () => {
    if (!selectedIds.value.length) return
    
    ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}条帖子吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        // await deletePost(selectedIds.value.join(','))
        ElMessage.success('批量删除成功')
        selectedIds.value = []
        getList()
      } catch (error) {
        console.error('批量删除失败:', error)
      }
    }).catch(() => {})
  }
  
  // 审核帖子
  const handleAudit = (postId, action) => {
    currentPostId.value = postId
    auditAction.value = action
    auditForm.reason = ''
    auditVisible.value = true
  }
  
  // 批量审核
  const handleBatchAudit = (action) => {
    if (!selectedIds.value.length) return
    
    currentPostId.value = null
    auditAction.value = action
    auditForm.reason = ''
    auditVisible.value = true
  }
  
  // 确认审核
  const handleConfirmAudit = async () => {
    try {
      const params = {
        ids: currentPostId.value ? [currentPostId.value] : selectedIds.value,
        status: auditAction.value === 1 ? 1 : 5,
        reason: auditForm.reason
      }
      
      if (currentPostId.value) {
        //await auditPost(currentPostId.value, params)
      } else {
        //await batchAuditPost(params)
      }
      
      ElMessage.success('操作成功')
      auditVisible.value = false
      selectedIds.value = []
      getList()
    } catch (error) {
      console.error('审核操作失败:', error)
    }
  }
  
  // 推荐帖子
  const handleRecommend = (row) => {
    console.log('推荐帖子:', row.id)
    ElMessage.success('推荐功能待开发')
  }
  
  // 查看数据统计
  const handleStatistics = (row) => {
    console.log('查看数据统计:', row.id)
    ElMessage.success('数据统计功能待开发')
  }
  
  // 导出数据
  const handleExport = () => {
    console.log('导出数据')
    ElMessage.success('导出功能待开发')
  }
  
  // 初始化
  onMounted(() => {
    fetchUsers() //加载当前登录用户信息
    getList()
  })

  // 点开帖子看详情弹窗，展示信息
const showNoteDetailDialog = async (note) => {
  debugger;
  // 转换数据格式
  const fatieid = note.userid;  // 发帖人的id
  const userId = users.value.id //当前登录用户的id

  const res = await request.post('/xhs/main/getMainList', {"id":note.id,"targettype":"1","userId":userId,"fatieid":fatieid})
  const main = res.data.records[0];
  const images = parseTags(main.imagesort)
  const talk = await request.post('/xhs/talk/getByContentid', {"contentid":main.id,"targettype":"2","userId":users.value.id})
  currentNote.value = {
    ...main,
    id: main.id,
    //images: [note.image], // 将单图片转为数组
    images: images, // 将单图片转为数组
    name: main.username,
    avatar: main.avatar,
    isFollowing: main.isFollowing === 0 ? false : true,// 是否关注
    followers: main.followers,   // 粉丝数量
    followListId: main.followListId,  // 关注表id
    content: main.description,
    collectioncount:main.collectioncount,
    comments: generateComments(talk)
  }
  currentImageIndex.value = 0
  showNoteDetail.value = true
}

// 生成评论数据结构
const generateComments =  (talk) => {
  
  const comments = []
  for (let i = 0; i < talk.data.length; i++) {
    comments.push({
      id: talk.data[i].id,
      isdianzan: talk.data[i].isdianzan === 0 ? false : true,// 是否点赞
      userid: talk.data[i].userid,
      contentid: talk.data[i].contentid,//
      username:  talk.data[i].username,
      avatar: talk.data[i].avatar,
      content: talk.data[i].content,
      createtime: talk.data[i].createtime,
      likes: talk.data[i].likes,
      depth:talk.data[i].depth,
      parentid:talk.data[i].parentid,
      images: talk.data[i].imageid ? [talk.data[i].imageid] : undefined
    })
  }
  return comments
}

// 计算嵌套评论结构
const nestedComments = computed(() => {
  const comments = currentNote.value.comments || [];
  // 获取一级评论 (depth=0)
  const topLevelComments = comments.filter(c => c.depth === 0);
  // 为每个一级评论添加 replies 属性
  return topLevelComments.map(comment => ({
    ...comment,
    replies: getReplies(comments, comment.id)
  }));
});

// 递归获取子评论
const getReplies = (comments, parentId) => {
  const replies = comments.filter(c => c.parentid === parentId);
  return replies.map(reply => ({
    ...reply,
    replies: getReplies(comments, reply.id) // 递归获取子评论
  }));
};

 // 帖子点赞，后台修改数据
 const followList = ref({
  userid: '', 
  followerid: '', 
  relationtype: '', 
  followername: '',  
  followeravatar:'',
  isliked:null,
  followListId:'',// 关注信息id 
})

// 关注作者
// const followAuthor = async() => {
//   currentNote.value.isFollowing = !currentNote.value.isFollowing
//   followList.value.userid = users.value.id, //当前用户id
//   followList.value.followerid = currentNote.value.userid, //当前帖子用户id
//   followList.value.relationtype = 1,  // 关系类型(1-普通粉丝,2-铁粉,3-好友,4-拉黑)
//   followList.value.followername = currentNote.value.username,
//   followList.value.followeravatar = currentNote.value.avatar,
//   followList.value.isliked = currentNote.value.isFollowing  //关注或者取消 
//   followList.value.followListId = currentNote.value.followListId // 关注信息id,用于删除
//   const main = await request.post('/xhs/followinglist/addOrDeletFollow', followList.value)
  
// }

 // 主页面点赞/取消点赞
 const toggleLike =  async(note) => {
  const user = userStore.getUser // 获取用户信息
  
  note.isliked = !note.isliked
  note.likes += note.isliked ? 1 : -1
  dz_Like.value.id = note.id,
  dz_Like.value.likes = note.likes
  dz_Like.value.userid = users.value.id  // 当前登录用户id 暂写死 待修改
  dz_Like.value.targettype = 1
  dz_Like.value.isliked = note.isliked
  const main = await request.post('/xhs/main/updateMain', dz_Like.value)
}

// 详情页面 点赞笔记
// const toggleLikeNote =async () => {
  
//   currentNote.value.isliked = !currentNote.value.isliked
//   currentNote.value.likes += currentNote.value.isliked ? 1 : -1

//   dz_Like.value.id = currentNote.value.id,
//   dz_Like.value.likes = currentNote.value.likes
//   dz_Like.value.userid =users.value.id  // 当前登录用户id 暂写死 待修改
//   dz_Like.value.targettype = 1
//   dz_Like.value.isliked = currentNote.value.isliked
//   const main = await request.post('/xhs/main/updateMain', dz_Like.value)
// }

// 收藏笔记
// const toggleFavorite =async () => {
//   currentNote.value.isFavorited = !currentNote.value.isFavorited
//   currentNote.value.collectioncount += currentNote.value.isFavorited ? 1 : -1

//   dz_Like.value.id = currentNote.value.id,
//   dz_Like.value.collectioncount = currentNote.value.collectioncount // 收藏数
//   dz_Like.value.userid =users.value.id  //  
//   dz_Like.value.targettype = 3   //目标类型(1-帖子 2-评论  3-收藏)
//   dz_Like.value.isliked = currentNote.value.isFavorited  //
//   const main = await request.post('/xhs/main/updateMain', dz_Like.value)
// }

// 评论点赞功能实现
const likeComment = async(comment) => {
      const aa = comment ;
      //findIndex 查找数组中是否有相同 id 的 comment。如果找到（index !== -1），就用新 comment 替换旧的,如果没找到（index === -1），就用 unshift 把新 comment 插入到数组开头。
      comment.isdianzan = !comment.isdianzan
      comment.likes += comment.isdianzan ? 1 : -1

      dz_Like.value.id = comment.contentid,  //帖子id
      dz_Like.value.talkid = comment.id,    // 评论id 
      dz_Like.value.commentcount = comment.likes // 评论数
      dz_Like.value.userid =users.value.id  //  
      dz_Like.value.targettype = 2   //目标类型(1-帖子 2-评论  3-收藏)
      dz_Like.value.isliked = comment.isdianzan  //点赞或取消点赞
      const main = await request.post('/xhs/main/updateMain', dz_Like.value)

      const index = currentNote.value.comments.findIndex(c => c.id === comment.id);
    if (index !== -1) {
      currentNote.value.comments[index] = comment; // 替换匹配到的 comment
    } else {
      currentNote.value.comments.unshift(comment); // 如果没有匹配到，就插入到开头
    }

}


// 提交评论
const submitComment = async (current) => {
  
  if (newComment.value.trim()) {
    const commentData = ref({
      userid: users.value.id, // 当前登录的用户 ID
      content: newComment.value, // 实际的评论内容
      contentid:current.id, // 实际的帖子 ID
      createtime: new Date(),
      usernickname:current.userid, // 实际的发帖人 ID
      likes: 0,
      depth: replyingTo.value ? 1 : 0,
      parentid: replyingTo.value  ? (replyingTo.value.depth === 1 ? replyingTo.value.parentid : replyingTo.value.id) : null,
      replyuserid: replyingTo.value === null ? null: replyingTo.value.userid ,   
      replyusername: replyingTo.value  === null ? null: replyingTo.value.username,
      imageid:''
    })
    const res = await request.post('/xhs/talk/saveTalk', commentData.value)
    currentNote.value.comments = res.data;
    cancelComment()
  }

}

// 回复评论
// const replyToComment = (comment) => {
  
//   replyingTo.value = {
//     id: comment.id, //评论id
//     depth: comment.depth, // 是否一级评论，0是，1否
//     parentid: comment.parentid, //一级评论id
//     userid: comment.userid,
//     username: comment.username
//   }
//   isInputFocused.value = true
// }

// 取消回复
const cancelReply = () => {
  replyingTo.value = null
}

// 取消评论
const cancelComment = () => {
  isInputFocused.value = false
  newComment.value = ''
  replyingTo.value = null
  textAreaRows.value = 1
}

// 分享笔记
const shareNote = () => {
  // 分享功能实现
  console.log('分享笔记')
}

// 插入@提及
const insertMention = () => {
  newComment.value += '@'
}

// 显示表情选择器
const showEmojiPicker = () => {
  // 显示表情选择器逻辑
  console.log('显示表情选择器')
}

// 显示收藏表情
const showFavoriteEmojis = () => {
  // 显示收藏表情逻辑
  console.log('显示收藏表情')
}

// 上传图片
const uploadImage = () => {
  imageInput.value.click()
}

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 处理图片上传逻辑
    console.log('上传图片:', file.name)
  }
}

const prevImage = () => {
  currentImageIndex.value = (currentImageIndex.value - 1 + currentNote.value.images.length) % currentNote.value.images.length
}

const nextImage = () => {
  currentImageIndex.value = (currentImageIndex.value + 1) % currentNote.value.images.length
}

const formatTime = (time) => {
  // 时间格式化
  return new Date(time).toLocaleString()
}

const closeDetail = () => {
  showNoteDetail.value = false
}

const checkMobile = () => {
  isMobile.value = window.innerWidth < 768
}



// 处理输入框聚焦
// const handleInputFocus = () => {
//   isInputFocused.value = true
// }

// 调整文本框高度
const adjustTextareaHeight = () => {
  const lineCount = (newComment.value.match(/\n/g) || []).length + 1
  textAreaRows.value = Math.min(Math.max(lineCount, 1), 4)
}

const parseTags = (tags) => {
    try {
      if (!tags) return [];
      return typeof tags === 'string' ? JSON.parse(tags) : tags;
    } catch (e) {
      return [];
    }
  };

  </script>
  
  <style lang="scss" scoped>
   

  .post-management-container {
    padding: 20px;

    .filter-container {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }
    
    .operation-container {
      margin-bottom: 20px;
      padding: 10px 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }
    
    .table-container {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
      
      :deep(.el-table) {
        .user-info-cell {
          display: flex;
          align-items: center;
          cursor: pointer;
          
          .username {
            margin-left: 10px;
          }
          
          &:hover {
            color: var(--el-color-primary);
          }
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: flex-end;
      padding: 10px 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }
  }

  /* 弹窗样式 */
  .note-detail-dialog {
    max-width: 99%;
    width: 1000px;
    height: 99vh;
    margin-top: 1vh !important;
  }

  .note-detail-container {
    display: flex;
    height: calc(80vh - 110px);
  }

   /* 左侧图片区域 - 全屏无间距 */
   .detail-left {
    flex: 3;
    padding: 0;
    margin: 0;
    overflow: hidden;
  }

  .image-container {
    position: relative;
    height: 100%;
    width: 100%;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .image-container img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }
  
  /* 右侧内容区域 */
  .detail-right {
    flex: 2;
    display: flex;
    flex-direction: column;
    position: relative;
  }
  
  .scroll-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
  }
  
  /* 固定评论框 */
  .fixed-comment-input {
    padding: 15px 20px;
    background-color: #fff;
    border-top: 1px solid #eee;
  }
  
  .comment-input {
    width: 100%;
  }
  
  /* 导航箭头 */
  .side-nav-arrows {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    pointer-events: none;
  }
  
  .nav-arrow {
    width: 40px;
    height: 40px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    cursor: pointer;
    pointer-events: auto;
    transition: all 0.3s ease;
    margin: 0 15px;
  }
  
  .nav-arrow:hover {
    background-color: rgba(0, 0, 0, 0.8);
  }
  
  .nav-arrow .el-icon {
    font-size: 20px;
  }
  
  /* 圆点指示器 */
  .dot-indicators {
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    gap: 8px;
  }
  
  .dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: rgba(216, 210, 210, 0.5);
    cursor: pointer;
    transition: all 0.3s ease;
  }
  
  .dot.active {
    background-color: #474747;
    transform: scale(1.2);
  }
  
  .dot:hover {
    background-color: rgba(78, 76, 76, 0.8);
  }
  
  /* 用户信息 */
  .user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  margin-bottom: 5px;
}
  
  .user-meta {
    flex: 1;
    margin-left: 15px;
    display: flex;
    flex-direction: column;
  }
   
  
  .follow-count {
    font-size: 12px;
    color: #999;
  }
  
  .follow-btn {
    margin-left: 10px;
    padding: 8px 15px;
  }
  
  /* 帖子内容 */
  .note-content h2 {
    margin-top: 0;
    margin-bottom: 5px;
  }
  
  .note-content p {
    white-space: pre-line;
    line-height: 1.6;
  }
  
  /* 评论区 */
  .comment-item {
    display: flex;
    margin-bottom: 5px;
    padding-bottom: 5px;
 
  }

  /* 回复信息样式 */
.reply-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f5f5f5;
  padding: 5px 10px;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

/* 正常模式样式 */
.comment-normal-mode {
  display: flex;
  align-items: center;
  gap: 10px;
}


.comment-input {
  flex: 1;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 25px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 3px;
  cursor: pointer;
  color: #666;
  font-size: 14px;
}

.action-item:hover {
  color: #333;
}

.icon {
  font-size: 18px;
}

.icon.liked {
  color: #ff2442;
}

.icon.dianzan {
  color: #ff2442;
}

.icon.favorited {
  color: #ff9500;
}

/* 编辑模式样式 */
.comment-edit-mode {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.comment-textarea {
  flex: 1;
}

.edit-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions {
  display: flex;
  gap: 7px;
}

.action-icon {
  font-size: 20px;
  color: #666;
  cursor: pointer;
}

.action-icon:hover {
  color: #333;
}

.right-actions {
  display: flex;
  gap: 1px;
}

.cancel-btn {
  border-radius: 20px;
  padding: 8px 15px;
}

.send-btn {
  border-radius: 20px;
  padding: 8px 20px;
  background: #ff2442;
  color: white;
}

.send-btn:disabled {
  background: #f5f5f5;
  color: #ccc;
}

.reply-mention {
  color: #888; /* 暗灰色 */
  font-size: 14px; /* 可选：调整字体大小 */
}

.comment-images img {
    max-width: 100px;
    max-height: 100px;
    margin-right: 5px;
    margin-top: 5px;
    cursor: pointer;
  }
  </style>